// 自定义脚本

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
  // 初始化工具提示
  if (typeof bootstrap !== 'undefined') {
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
  }
  
  // 初始化下拉菜单
  const dropdownToggleList = document.querySelectorAll('.dropdown-toggle');
  dropdownToggleList.forEach(toggle => {
    toggle.addEventListener('click', function(e) {
      e.preventDefault();
      const parent = this.closest('.dropdown');
      const menu = parent.querySelector('.dropdown-menu');
      menu.classList.toggle('show');
    });
  });
  
  // 点击其他地方关闭下拉菜单
  document.addEventListener('click', function(e) {
    if (!e.target.closest('.dropdown')) {
      document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
        menu.classList.remove('show');
      });
    }
  });
  
  // 表单验证增强
  const forms = document.querySelectorAll('form');
  forms.forEach(form => {
    form.addEventListener('submit', function(e) {
      const requiredFields = this.querySelectorAll('[required]');
      let isValid = true;
      
      requiredFields.forEach(field => {
        if (!field.value.trim()) {
          isValid = false;
          field.classList.add('is-invalid');
          
          // 添加错误提示
          if (!field.nextElementSibling || !field.nextElementSibling.classList.contains('invalid-feedback')) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'invalid-feedback';
            errorDiv.textContent = '此字段为必填项';
            field.parentNode.appendChild(errorDiv);
          }
        } else {
          field.classList.remove('is-invalid');
          const errorDiv = field.nextElementSibling;
          if (errorDiv && errorDiv.classList.contains('invalid-feedback')) {
            errorDiv.remove();
          }
        }
      });
      
      // 邮箱格式验证
      const emailFields = this.querySelectorAll('[type="email"]');
      emailFields.forEach(field => {
        if (field.value.trim() && !validateEmail(field.value.trim())) {
          isValid = false;
          field.classList.add('is-invalid');
          
          // 添加错误提示
          if (!field.nextElementSibling || !field.nextElementSibling.classList.contains('invalid-feedback')) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'invalid-feedback';
            errorDiv.textContent = '请输入有效的邮箱地址';
            field.parentNode.appendChild(errorDiv);
          }
        }
      });
      
      if (!isValid) {
        e.preventDefault();
        e.stopPropagation();
      }
    });
    
    // 输入时移除错误状态
    const inputs = form.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
      input.addEventListener('input', function() {
        this.classList.remove('is-invalid');
        const errorDiv = this.nextElementSibling;
        if (errorDiv && errorDiv.classList.contains('invalid-feedback')) {
          errorDiv.remove();
        }
      });
    });
  });
  
  // 侧边栏折叠功能（移动端）
  const sidebarToggle = document.querySelector('.navbar-toggler');
  if (sidebarToggle) {
    sidebarToggle.addEventListener('click', function() {
      const sidebar = document.querySelector('.sidebar');
      sidebar.classList.toggle('d-none');
      sidebar.classList.toggle('d-block');
    });
  }
  
  // 批量操作功能
  const selectAll = document.querySelector('.select-all');
  if (selectAll) {
    selectAll.addEventListener('change', function() {
      const checkboxes = document.querySelectorAll('.item-checkbox');
      checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
      });
    });
  }
  
  // 动态表格行悬停效果
  const tableRows = document.querySelectorAll('tbody tr');
  tableRows.forEach(row => {
    row.addEventListener('mouseenter', function() {
      this.style.backgroundColor = '#f8f9fa';
    });
    row.addEventListener('mouseleave', function() {
      this.style.backgroundColor = '';
    });
  });
});

// 邮箱验证函数
function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(String(email).toLowerCase());
}

// 数字格式化函数
function formatNumber(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 日期格式化函数
function formatDate(date) {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 复制到剪贴板功能
function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
  
  // 显示复制成功提示
  showToast('复制成功');
}

// 显示提示消息
function showToast(message, type = 'success') {
  // 创建toast元素
  const toast = document.createElement('div');
  toast.className = `toast position-fixed top-50 start-50 translate-middle bg-${type} text-white px-4 py-2 rounded`;
  toast.textContent = message;
  
  // 添加到文档
  document.body.appendChild(toast);
  
  // 显示toast
  toast.style.display = 'block';
  
  // 2秒后移除
  setTimeout(() => {
    toast.style.opacity = '0';
    toast.style.transition = 'opacity 0.5s';
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 500);
  }, 2000);
}